<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="output"></div>
</body>
<script>
    class StreamFetcher {
        constructor(url, options = {}) {
            this.url = url;
            this.options = options;
            this.controller = new AbortController();
            this.isCancelled = false;
        }

        async start(onData, onError, onComplete) {
            try {
                const response = await fetch(this.url, {
                    ...this.options,
                    signal: this.controller.signal,
                    headers: {
                        'Content-Type': 'application/json',
                        ...this.options.headers
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    if (this.isCancelled) {
                        reader.cancel();
                        break;
                    }

                    const {done, value} = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value, {stream: true});
                    onData(chunk);
                }

                onComplete();
            } catch (error) {
                if (!this.isCancelled) {
                    onError(error);
                }
            }
        }

        cancel() {
            this.isCancelled = true;
            this.controller.abort();
        }
    }

    // 使用示例
    const stream = new StreamFetcher('http://127.0.0.1:8099/openai/streamFunction2', {
        method: 'POST',
        headers: generateHeaders(),
        body: "你好啊AI"
    });

    stream.start(
        chunk => {
            console.log('Received:', chunk);
            document.getElementById('output').innerText += chunk;
        },
        error => console.error('Error:', error),
        () => console.log('Stream completed')
    );

    function generateHeaders() {
        const token = localStorage.getItem('authToken');
        return {
            'chatId': '12345678',
            'settingId': `7`,
            'userId': '274795671465279488',
            'Content-Type': 'text/event-stream',
            'X-ZQ-Ignore': '1'
        };
    }

    // 需要取消时调用
    // stream.cancel();
</script>
</html>
